const { ApiKeys } = require('../models');
const { validationResult } = require('express-validator');
const logger = require('../utils/logger');

class ApiKeysController {
  /**
   * 获取列表
   */
  async getList(req, res) {
    try {
      const { page = 1, limit = 10, ...filters } = req.query;
      const offset = (page - 1) * limit;

      const { count, rows } = await ApiKeys.findAndCountAll({
        where: filters,
        limit: parseInt(limit),
        offset: parseInt(offset),
        order: [['created_at', 'DESC']]
      });

      res.json({
        success: true,
        data: {
          list: rows,
          pagination: {
            page: parseInt(page),
            limit: parseInt(limit),
            total: count,
            pages: Math.ceil(count / limit)
          }
        }
      });
    } catch (error) {
      logger.error('获取ApiKeys列表失败:', error);
      res.status(500).json({
        success: false,
        message: '获取列表失败',
        error: error.message
      });
    }
  }

  /**
   * 获取详情
   */
  async getDetail(req, res) {
    try {
      const { id } = req.params;

      const item = await ApiKeys.findByPk(id);
      if (!item) {
        return res.status(404).json({
          success: false,
          message: '记录不存在'
        });
      }

      res.json({
        success: true,
        data: item
      });
    } catch (error) {
      logger.error('获取ApiKeys详情失败:', error);
      res.status(500).json({
        success: false,
        message: '获取详情失败',
        error: error.message
      });
    }
  }

  /**
   * 创建记录
   */
  async create(req, res) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '参数验证失败',
          errors: errors.array()
        });
      }

      const data = req.body;
      const item = await ApiKeys.create(data);

      res.status(201).json({
        success: true,
        message: '创建成功',
        data: item
      });
    } catch (error) {
      logger.error('创建ApiKeys失败:', error);
      res.status(500).json({
        success: false,
        message: '创建失败',
        error: error.message
      });
    }
  }

  /**
   * 更新记录
   */
  async update(req, res) {
    try {
      const { id } = req.params;
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '参数验证失败',
          errors: errors.array()
        });
      }

      const item = await ApiKeys.findByPk(id);
      if (!item) {
        return res.status(404).json({
          success: false,
          message: '记录不存在'
        });
      }

      const data = req.body;
      await item.update(data);

      res.json({
        success: true,
        message: '更新成功',
        data: item
      });
    } catch (error) {
      logger.error('更新ApiKeys失败:', error);
      res.status(500).json({
        success: false,
        message: '更新失败',
        error: error.message
      });
    }
  }

  /**
   * 删除记录
   */
  async delete(req, res) {
    try {
      const { id } = req.params;

      const item = await ApiKeys.findByPk(id);
      if (!item) {
        return res.status(404).json({
          success: false,
          message: '记录不存在'
        });
      }

      await item.destroy();

      res.json({
        success: true,
        message: '删除成功'
      });
    } catch (error) {
      logger.error('删除ApiKeys失败:', error);
      res.status(500).json({
        success: false,
        message: '删除失败',
        error: error.message
      });
    }
  }

  /**
   * 批量删除
   */
  async batchDelete(req, res) {
    try {
      const { ids } = req.body;

      if (!Array.isArray(ids) || ids.length === 0) {
        return res.status(400).json({
          success: false,
          message: '请选择要删除的记录'
        });
      }

      await ApiKeys.destroy({
        where: {
          id: ids
        }
      });

      res.json({
        success: true,
        message: `成功删除 ${ids.length} 条记录`
      });
    } catch (error) {
      logger.error('批量删除ApiKeys失败:', error);
      res.status(500).json({
        success: false,
        message: '批量删除失败',
        error: error.message
      });
    }
  }
}

module.exports = new ApiKeysController();
